﻿using FTBS.Common;
using FTBS.Models.BLO;
using FTBS.Models.Entities;
using FTBS.Models.Entities.Concert;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FTBS.Controllers
{
    public class CheckOutController : Controller
    {
        private ChairBLO _bloChair = new ChairBLO();
        private TicketBLO _bloTicket = new TicketBLO();
        private CheckOutBLO _checkoutBLO = new CheckOutBLO();
        private ScheduleBLO _scheduleBLO = new ScheduleBLO();
        private ShowTimeBLO _showtimeBLO = new ShowTimeBLO();
        private FilmBLO _filmBLO = new FilmBLO();
        private TheaterBLO _theaterBlo = new TheaterBLO();
        private RoomBLO _roomBlo = new RoomBLO();

        public ActionResult Index(SearchSchedule searchSchedule)
        {
            if (this.Session["SearchSchedule"] != null)
            {
                searchSchedule = this.Session["SearchSchedule"] as SearchSchedule;
            }
            else { return Redirect("/Schedule"); }
         

            if (this.Session["RoleName"] != null)
            {
                searchSchedule.User.FullName = this.Session["Account"].ToString().Trim();
                searchSchedule.User.Email = this.Session["Email"].ToString().Trim();
                searchSchedule.User.PhoneNumber = this.Session["Number"].ToString().Trim();
            }
            Theater theater = new Theater();

            theater = _theaterBlo.GetTheaterById(searchSchedule.TheaterId);
            var totalSecond = theater.TimeForBooking * 60;

            if (searchSchedule.TimeBooking == DateTime.MinValue)
            {
                searchSchedule.TimeBooking = DateTime.Now;
                ViewBag.TimeForBooking = totalSecond;
            }
            else
            {
                DateTime timeBooking = searchSchedule.TimeBooking;
                ViewBag.TimeForBooking = timeBooking.AddMinutes((double)theater.TimeForBooking).Subtract(DateTime.Now).TotalSeconds;
            }

            ViewBag.User = searchSchedule;
            ViewBag.Showtime = _showtimeBLO.LoadShowTime(searchSchedule.ShowTimeId);
            ViewBag.Film = _filmBLO.LoadFilmsById(searchSchedule.FilmId);
            ViewBag.TicketList = _bloTicket.getListTicketById(searchSchedule.ScheduleId);
            ViewBag.TheaterId = searchSchedule.TheaterId;
            ViewBag.Schedule = _scheduleBLO.GetScheduleById(searchSchedule.ScheduleId);
            ViewBag.Room = _roomBlo.GetRoomById(searchSchedule.RoomId);
            return View(_bloChair.LoadChairs(searchSchedule.RoomId));
        }

        /// <summary>
        /// Load payment
        /// </summary>
        /// <param name="listId"></param>
        /// <returns></returns>
        /// <author>Nguyen</author>
        /// <edit>VuongVT</edit>
        /// <reason>Add roomId of session</reason>
        /// 
        [HttpPost]
        public ActionResult Payment(string listId, string pos, string fullName, string phoneNumber, string Email)
        {
            SearchSchedule searchSchedule = new SearchSchedule();
            searchSchedule = this.Session["SearchSchedule"] as SearchSchedule;
            listId = listId.Remove(listId.Length - 1);
            string[] strListTicket = listId.Split(' ');
            this.Session["Info"] = fullName + " " + phoneNumber + " " + Email;
            searchSchedule.FullName = fullName;
            searchSchedule.Email = Email;
            searchSchedule.PhoneNumber = phoneNumber;

            //Check list ticketId selected is booked or not
            var isBookedTicket = _checkoutBLO.IsBookedTicket(strListTicket);
            //Calculate total price
            double totalPrice = _checkoutBLO.TotalPrice(strListTicket);
            searchSchedule.TotalPrice = totalPrice;
            //Get list possition 
            searchSchedule.Position = pos;
            searchSchedule.TicketId = listId;
            this.Session["SearchSchedule"] = searchSchedule;
            if (isBookedTicket)
            {
                //tra ve message k thanh cong
                return Redirect("Index");
            }
            else
            {
                return Redirect("PaymentService");
            }
        }

        public string CheckSameChairs(string listId)
        {

            listId = listId.Remove(listId.Length - 1);
            string[] strListTicket = listId.Split(' ');
            //Check list ticketId selected is booked or not
            var isBookedTicket = _checkoutBLO.IsBookedTicket(strListTicket);
            if (!isBookedTicket)
            {
                return "false";
            }
            else
            { return "true"; }
        }

        /// <summary>
        /// defend on schedule to call payment
        /// </summary>
        /// <returns></returns>
        public ActionResult PaymentService()
        {
            var searchSchedule = this.Session["SearchSchedule"] as SearchSchedule;
            var Info = this.Session["Info"] as String;
            ViewBag.Info = Info;
            ViewBag.CartId = _checkoutBLO.GenerateCodeBooking();
            ViewBag.Film = _filmBLO.LoadFilmsById(searchSchedule.FilmId);
            ViewBag.TheaterName = _theaterBlo.GetTheaterById(searchSchedule.TheaterId).TheaterName;
            ViewBag.ShowTime = _showtimeBLO.GetShowTimeById(searchSchedule.ShowTimeId);
            ViewBag.Schedule = _scheduleBLO.GetScheduleById(searchSchedule.ScheduleId);
            ViewBag.RoomName = _roomBlo.GetRoomById(searchSchedule.RoomId).RoomName;
            //Get Promotion
            Promotion promotionValue = new Promotion();
            promotionValue = _scheduleBLO.GetPromotionByScheduleId(_scheduleBLO.GetScheduleById(searchSchedule.ScheduleId));
            searchSchedule.Promotion = promotionValue;
            //If have promotion -> count again totalPrice
            if (promotionValue != null)
            {
                searchSchedule.TotalPrice = searchSchedule.TotalPrice - ((searchSchedule.TotalPrice * promotionValue.Rate) / 100);
            }

            string[] listTicket = searchSchedule.TicketId.Split(' ');
            ViewBag.TotalTicket = listTicket.Length;

            Theater theater = new Theater();
            theater = _theaterBlo.GetTheaterById(searchSchedule.TheaterId);
            var totalSecond = theater.TimeForBooking * 60;

            if (searchSchedule.TimeForPayment == DateTime.MinValue)
            {
                searchSchedule.TimeForPayment = DateTime.Now;
                ViewBag.TimeForPayment = totalSecond;
            }
            else
            {
                DateTime timeBooking = searchSchedule.TimeForPayment;
                ViewBag.TimeForPayment = timeBooking.AddMinutes((double)theater.TimeForBooking).Subtract(DateTime.Now).TotalSeconds;
            }

            return View(searchSchedule);
        }



        public ActionResult ReceiveValue(string transaction_info, string order_code, string price, string payment_id, string payment_type, string error_text, string secure_code)
        {

            NL_CheckOut nl = new NL_CheckOut();
            bool result = nl.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);

            SearchSchedule searchSchedule = this.Session["SearchSchedule"] as SearchSchedule;
            ViewBag.OrderCode = order_code;
            ViewBag.Film = _filmBLO.LoadFilmsById(searchSchedule.FilmId);
            ViewBag.TheaterName = _theaterBlo.GetTheaterById(searchSchedule.TheaterId).TheaterName;
            ViewBag.ShowTime = _showtimeBLO.GetShowTimeById(searchSchedule.ShowTimeId);
            ViewBag.Schedule = _scheduleBLO.GetScheduleById(searchSchedule.ScheduleId);
            ViewBag.RoomName = _roomBlo.GetRoomById(searchSchedule.RoomId).RoomName;
            string[] listTicket = searchSchedule.TicketId.Split(' ');
            ViewBag.TotalTicket = listTicket.Length;

            if (!result)
            {
                var actualMoneyReceive = searchSchedule.TotalPrice;
                string listId = searchSchedule.TicketId;
                string[] strListTicket = listId.Split(' ');
                //Check list ticketId selected is booked or not
                var isBookedTicket = _checkoutBLO.IsBookedTicket(strListTicket);
                if (isBookedTicket && searchSchedule.IsPaymentSuccessfulPage == false)
                {
                    searchSchedule.IsPaymentSuccessfulPage = false;
                    searchSchedule.IsBooked = true;
                    var resultBookingFail = _checkoutBLO.BookingTicketForFailPayment(searchSchedule, actualMoneyReceive, order_code);                    
                    return View("FailPayment", searchSchedule);
                }
                else
                {
                    if (searchSchedule.IsBooked == false)
                    {
                        var resultBooking = _checkoutBLO.BookingTicket(searchSchedule, actualMoneyReceive, order_code);

                        if (resultBooking == true)
                        {
                            searchSchedule.IsPaymentSuccessfulPage = true;
                            searchSchedule.IsBooked = true;
                            searchSchedule.IsNotified = false;                            
                            return View(searchSchedule);
                        }
                        else
                        {
                            return HttpNotFound();
                        }
                    }
                    else if (searchSchedule.IsBooked == true)
                    {
                        if (searchSchedule.IsPaymentSuccessfulPage == true)
                        {
                            searchSchedule.IsNotified = true;
                            return View(searchSchedule);
                        }
                    }
                }
            }
            return View("FailServicePayment", searchSchedule);
        }

        public ActionResult SuccessfulPayment(string orderCode)
        {
            SearchSchedule searchSchedule = this.Session["SearchSchedule"] as SearchSchedule;
            ViewBag.CartId = orderCode;
            ViewBag.Film = _filmBLO.LoadFilmsById(searchSchedule.FilmId);
            ViewBag.TheaterName = _theaterBlo.GetTheaterById(searchSchedule.TheaterId).TheaterName;
            ViewBag.ShowTime = _showtimeBLO.GetShowTimeById(searchSchedule.ShowTimeId);
            ViewBag.Schedule = _scheduleBLO.GetScheduleById(searchSchedule.ScheduleId);
            ViewBag.RoomName = _roomBlo.GetRoomById(searchSchedule.RoomId).RoomName;
            string[] listTicket = searchSchedule.TicketId.Split(' ');
            ViewBag.TotalTicket = listTicket.Length;

            var actualMoneyReceive = searchSchedule.TotalPrice;
            string listId = searchSchedule.TicketId;
            string[] strListTicket = listId.Split(' ');
            //Check list ticketId selected is booked or not
            var isBookedTicket = _checkoutBLO.IsBookedTicket(strListTicket);
            if (isBookedTicket && searchSchedule.IsPaymentSuccessfulPage == false)
            {
                searchSchedule.IsPaymentSuccessfulPage = false;
                searchSchedule.IsBooked = true;
                var resultBookingFail = _checkoutBLO.BookingTicketForFailPayment(searchSchedule, actualMoneyReceive, orderCode);
                return View("FailPayment", searchSchedule);
            }
            else
            {
                if (searchSchedule.IsBooked == false)
                {
                    var resultBooking = _checkoutBLO.BookingTicket(searchSchedule, actualMoneyReceive, orderCode);
                    if (resultBooking == true)
                    {
                        searchSchedule.IsPaymentSuccessfulPage = true;
                        searchSchedule.IsBooked = true;
                        searchSchedule.IsNotified = false;
                        return View(searchSchedule);
                    }
                    else
                    {
                        return HttpNotFound();
                    }
                }
                else if (searchSchedule.IsBooked == true)
                {
                    if (searchSchedule.IsPaymentSuccessfulPage == true)
                    {
                        searchSchedule.IsNotified = true;
                        return View(searchSchedule);
                    }
                }
            }
            return HttpNotFound();
        }


    }
}
